package com.dz.listener;

import com.rabbitmq.client.Channel;
import com.dz.constant.RabbitMQConstant;
import com.dz.constant.RedisConstant;
import com.dz.redis.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.retry.MessageRecoverer;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author 鄧浩奇
 * @classname RabbitMQListener
 * @description 监听Long队列
 * @since 2024/3/28 17:15
 **/

@Slf4j
//@Component
public class RabbitMQListener implements MessageRecoverer {

    private final RedisCache redisCache;

    @Autowired
    public RabbitMQListener(RedisCache redisCache) {
        this.redisCache = redisCache;
    }

    @RabbitListener(queues = RabbitMQConstant.SKY_Long_QUEUE)
    public void longQueueListener(Long id, Channel channel, Message message) throws Exception {
        log.info("处理消息：消息id: {}", id);

        // 通知redis删除缓存
        boolean isDeleteSuccess = redisCache.deleteObject(RedisConstant.DISH_ + id.toString());
        if (isDeleteSuccess) {
            // 成功删除，返回确认信息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } else {
            // 抛出异常 进行重试
            log.info("出现异常,正在重试......");
            throw new Exception();

        }

    }


    @Override
    public void recover(Message message, Throwable cause) {
        log.error("重试次数达到上限.....");
    }
}
